package api

import (
	"net/http"
	"encoding/json"
	"io/ioutil"
	"go-web/model"
	"strconv"
	"time"
	"fmt"
	"go-web/web"
)

func MsgHandler() web.WebHandler  {
	return func(writer http.ResponseWriter, request *http.Request) {
		writer.Header().Set("Content-Type", "application/json")
		request.ParseForm()
		method := request.Method

		rps,_ := json.Marshal(ERROR)
		if method == POST {
			reqs,err := ioutil.ReadAll(request.Body)
			if err != nil {
				rps,_ = json.Marshal(PARAM_ERROR)
				writer.Write(rps)
				return
			}
			var msg model.Msg
			err = json.Unmarshal(reqs, &msg)
			if err != nil {
				fmt.Println(err)
				rps,_ = json.Marshal(PARAM_CONV_ERROR)
				writer.Write(rps)
				return
			}
			msg.CTime = time.Now()
			_,err = msg.Save()
			if err != nil {
				writer.Write(rps)
				return
			}

			data := make(map[string]int)
			data["id"] = msg.Id

			datas := buildSuccess()
			datas.Datas = data

			reps,err := json.Marshal(datas)
			if err != nil {
				writer.Write(rps)
				return
			}

			writer.Write(reps)
		} else if method == PUT {
			idstr := request.Form.Get("id")
			if idstr == "" {
				rps,_ = json.Marshal(PARAM_ERROR)
				writer.Write(rps)
				return
			}
		} else if method == GET {
			idstr := request.Form.Get("id")
			if idstr == "" {
				msg := &model.Msg{}
				msgs,err := msg.Query()
				if err != nil {
					rps,_ = json.Marshal(SUCCESS)
					writer.Write(rps)
					return
				}
				datas := buildSuccess()
				datas.Datas = msgs
				rps,_ = json.Marshal(datas)
				writer.Write(rps)
			} else {
				id,err := strconv.Atoi(idstr)
				if err != nil {
					rps,_ = json.Marshal(PARAM_ERROR)
					writer.Write(rps)
					return
				}
				msg := &model.Msg{Id:id}
				msg,err = msg.GetById()
				if err != nil {
					writer.Write(rps)
					return
				}

				datas := buildSuccess()
				datas.Datas = msg

				rps,_ = json.Marshal(datas)
				writer.Write(rps)
			}
		}
	}
}
